package org.example.myleet.p662;

import org.example.myleet.Utils.TreeNode;

import java.util.LinkedList;
import java.util.Queue;

public class Solution {
    public int widthOfBinaryTree(TreeNode root) {
        long maxWidth = 0;
        Queue<Long> idQueue = new LinkedList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        idQueue.offer(1L);
        while (!queue.isEmpty()) {
            int size = queue.size();
            long minId = Long.MAX_VALUE;
            long maxId = Long.MIN_VALUE;
            for (int i = 0; i < size; ++i) {
                TreeNode node = queue.poll();
                Long id = idQueue.poll();
                minId = Math.min(minId, id);
                maxId = Math.max(maxId, id);
                if (null != node.left) {
                    queue.offer(node.left);
                    idQueue.offer(id * 2);
                }
                if (null != node.right) {
                    queue.offer(node.right);
                    idQueue.offer(id * 2 + 1);
                }
            }
            maxWidth = Math.max(maxWidth, maxId - minId + 1);
        }
        return (int) maxWidth;
    }
}
